<template>
  <div class="app-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="6">
        <el-card>
          <div class="statistic-card">
            <div class="statistic-title">在线设备</div>
            <div class="statistic-value">{{ onlineDeviceCount }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="statistic-card">
            <div class="statistic-title">总连接数</div>
            <div class="statistic-value">{{ totalConnections }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="statistic-card">
            <div class="statistic-title">消息发送</div>
            <div class="statistic-value">{{ totalSentMessages }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="statistic-card">
            <div class="statistic-title">消息接收</div>
            <div class="statistic-value">{{ totalReceivedMessages }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-refresh" size="mini" @click="refreshDeviceInfo">刷新设备信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-download" size="mini"
          @click="syncOnlineDevices">同步在线设备</el-button>
      </el-col>
    </el-row>

    <!-- 在线设备列表 -->
    <el-table v-loading="loading" :data="deviceList" height="600" stripe border>
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="客户端ID" align="center" prop="clientid" width="180" show-overflow-tooltip />
      <el-table-column label="用户名" align="center" prop="username" width="120" show-overflow-tooltip />
      <el-table-column label="IP地址" align="center" prop="ip_address" width="140" />
      <el-table-column label="端口" align="center" prop="port" width="80" />
      <el-table-column label="连接状态" align="center" prop="connected" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.connected" type="success" size="small">已连接</el-tag>
          <el-tag v-else type="danger" size="small">已断开</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="连接时间" align="center" prop="connected_at" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.connected_at, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="协议版本" align="center" prop="proto_ver" width="100" />
      <el-table-column label="协议名称" align="center" prop="proto_name" width="100" />
      <el-table-column label="保活时间(s)" align="center" prop="keepalive" width="110" />
      <el-table-column label="节点" align="center" prop="node" width="150" show-overflow-tooltip />
      <el-table-column label="监听器" align="center" prop="listener" width="120" />
      <el-table-column label="接收消息" align="center" prop="recv_msg" width="100" />
      <el-table-column label="发送消息" align="center" prop="send_msg" width="100" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleViewDetail(scope.row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getDeviceList" />
    <!-- 设备详情对话框 -->
    <el-dialog title="设备详情" :visible.sync="detailDialogVisible" width="80%" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="客户端ID">{{ selectedDevice.clientid }}</el-descriptions-item>
        <el-descriptions-item label="用户名">{{ selectedDevice.username }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ selectedDevice.ip_address }}</el-descriptions-item>
        <el-descriptions-item label="端口">{{ selectedDevice.port }}</el-descriptions-item>
        <el-descriptions-item label="协议名称">{{ selectedDevice.proto_name }}</el-descriptions-item>
        <el-descriptions-item label="协议版本">{{ selectedDevice.proto_ver }}</el-descriptions-item>
        <el-descriptions-item label="保活时间">{{ selectedDevice.keepalive }}秒</el-descriptions-item>
        <el-descriptions-item label="清理会话">{{ selectedDevice.clean_start ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="接收消息数">{{ selectedDevice.recv_msg }}</el-descriptions-item>
        <el-descriptions-item label="发送消息数">{{ selectedDevice.send_msg }}</el-descriptions-item>
        <el-descriptions-item label="接收字节数">{{ selectedDevice.recv_oct }}</el-descriptions-item>
        <el-descriptions-item label="发送字节数">{{ selectedDevice.send_oct }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import { getDeviceInfo, addOnlineDevices } from "@/api/emqx/emqxClient"

export default {
  name: "EmqxMonitor",
  components: {
    // 如果项目中有分页组件，取消注释
    // Pagination: () => import('@/components/Pagination')
  },
  data() {
    return {
      loading: false,
      deviceList: [],
      selectedDevice: {},
      detailDialogVisible: false,
      refreshTimer: null,
      // 新增分页数据
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 20
      }
    };
  },
  computed: {
    onlineDeviceCount() {
      return this.deviceList.filter(device => device.connected).length;
    },
    totalConnections() {
      return this.deviceList.length;
    },
    totalSentMessages() {
      return this.deviceList.reduce((total, device) => total + (device.send_msg || 0), 0);
    },
    totalReceivedMessages() {
      return this.deviceList.reduce((total, device) => total + (device.recv_msg || 0), 0);
    }
  },
  created() {
    this.getDeviceList();
    this.startAutoRefresh();
  },
  beforeDestroy() {
    this.stopAutoRefresh();
  },
  methods: {
    /** 获取设备列表 */
    getDeviceList() {
      this.loading = true;
      getDeviceInfo().then(response => {
        console.log('API响应:', response);
        if (response.code === 200) {
          this.deviceList = response.data || [];
          console.log('设备列表:', this.deviceList);
        } else {
          this.$message.error('获取设备信息失败: ' + response.msg);
        }
        this.loading = false;
      }).catch(error => {
        console.error('API调用错误:', error);
        this.$message.error('网络请求失败');
        this.loading = false;
      });
    },
    /** 刷新设备信息 */
    refreshDeviceInfo() {
      this.getDeviceList();
      this.$message.success("刷新成功");
    },
    /** 同步在线设备 */
    syncOnlineDevices() {
      this.$modal.confirm('是否确认同步所有在线设备信息到数据库？').then(() => {
        return addOnlineDevices();
      }).then((response) => {
        this.$modal.msgSuccess(response.msg || "同步成功");
        this.getDeviceList();
      }).catch(() => { });
    },
    /** 查看设备详情 */
    handleViewDetail(row) {
      this.selectedDevice = row;
      this.detailDialogVisible = true;
    },
    /** 开始自动刷新 */
    startAutoRefresh() {
      this.refreshTimer = setInterval(() => {
        this.getDeviceList();
      }, 30000); // 30秒刷新一次
    },
    /** 停止自动刷新 */
    stopAutoRefresh() {
      if (this.refreshTimer) {
        clearInterval(this.refreshTimer);
        this.refreshTimer = null;
      }
    }
  }
};
</script>

<style scoped>
.statistic-card {
  text-align: center;
  padding: 20px;
}

.statistic-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.statistic-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.mb20 {
  margin-bottom: 20px;
}
</style>